import { IImportData, IListItem, ImportMode } from '@/utils/interfaces'
import { apiStore } from '@/utils/store/apiStore'
import { Button, Form, Message, Radio } from '@arco-design/web-react'
import React from 'react'
import SelectGroup, { ISelectGroupState } from '../../../components/SelectGroup'
import ApiListSelect from '../ApiListSelect'
import { filterWithParentId } from '../parentIdHandler'
import { checkExistItems } from './checkExistItems'
import ImFromFile from './ImFromFile'
import ImFromSwaggerJsonUrl from './ImFromSwaggerJsonUrl'
import {
    checkExistImFromYapiPage,
    imFromYapiPageDataToApiItems,
} from './ImFromYapiPage'
import ImFromYapiUrl from './ImFromYapiUrl'

export interface IImportProps {
    // 导入完成后
    afterImported?: () => void
    // ref对象
}

const Import: React.FC<IImportProps> = ({ afterImported }) => {
    // 模式
    const [mode, setMode] = useState<IImportData['mode']>(
        ImportMode.mockResponseExportFile,
    )
    // 导入预览
    const [preview, setPreview] = useState<IListItem[]>([])
    // 选中的行
    const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([])
    // 位置
    const [position, setPosition] = useState<ISelectGroupState>({
        id: [''],
        addGroup: true,
        newGroupName: '未命名',
    })

    // 处理预览数据
    const handlePreview = (
        items: IListItem[],
        recommendGroupOptions?: Partial<ISelectGroupState>,
    ) => {
        setPreview(items)
        setSelectedRowKeys([])
        if (recommendGroupOptions) {
            setPosition({
                ...position,
                ...recommendGroupOptions,
            })
        }
    }

    // 获取导入组件
    const getImportComponent = () => {
        if (mode === 'swagger-json-url') {
            return <ImFromSwaggerJsonUrl onPreview={handlePreview} />
        }
        if (mode === 'mock-response-export-file') {
            return <ImFromFile onPreview={handlePreview} />
        }
        if (mode === 'yapi-url') {
            return <ImFromYapiUrl onPreview={handlePreview} />
        }
        return null
    }

    // 导入
    const handleImport = async () => {
        // 准备好一个分组
        let itemsParentId = position.id?.[position.id.length - 1] || ''
        const pushedItems: IListItem[] = []
        if (position.addGroup) {
            const groupId = randomStr()
            const group: IGroupItem = {
                id: groupId,
                label: position?.newGroupName || '未命名',
                type: 'group',
                parentId: itemsParentId,
                enabled: true,
            }
            pushedItems.push(group)
            itemsParentId = groupId
        }

        const selected = filterWithParentId(
            preview,
            selectedRowKeys,
            itemsParentId,
        )
        pushedItems.push(...selected)
        // 检查重复项
        const finalPushedItems = await checkExistItems(pushedItems)
        if (!finalPushedItems) {
            return
        }
        await apiStore.saveBatch(finalPushedItems)
        setSelectedRowKeys([])
        Message.success('导入成功')
        afterImported?.()
    }

    // 检查是否存在从YAPI页面导入，存在时进行导入
    const checkImFromYapiPageHandle = async () => {
        const exist = await checkExistImFromYapiPage()
        if (!exist) return
        const yapiPageApiItems = await imFromYapiPageDataToApiItems()
        if (!yapiPageApiItems) return
        const { apiItems, recommendGroupName } = yapiPageApiItems
        setMode(ImportMode.yapiPage)
        setPreview(apiItems)
        setPosition({
            id: [''],
            addGroup: true,
            newGroupName: recommendGroupName || '未命名',
        })
    }

    useEffect(() => {
        checkImFromYapiPageHandle()
    }, [])

    return (
        <div>
            {/* 模式 */}
            <Form.Item label='模式' required>
                <Radio.Group
                    value={mode}
                    onChange={(value) => {
                        setMode(value)
                        setPreview([])
                        setSelectedRowKeys([])
                    }}
                >
                    {/* <Radio value='yapi-url'>YApi URL</Radio> */}
                    <Radio value={ImportMode.mockResponseExportFile}>
                        Mock Response Export File
                    </Radio>
                    <Radio value={ImportMode.swaggerJsonUrl}>
                        Swagger JSON URL
                    </Radio>
                    <Radio value={ImportMode.yapiUrl}>YAPI</Radio>
                    {mode === ImportMode.yapiPage && (
                        <Radio value={ImportMode.yapiPage}>YAPI 页面</Radio>
                    )}
                </Radio.Group>
            </Form.Item>
            {getImportComponent()}
            <div className='mb-4'>
                <ApiListSelect
                    selectedRowKeys={selectedRowKeys}
                    onSelectedRowKeysChange={setSelectedRowKeys}
                    data={preview}
                />
            </div>
            {/* 位置 */}
            <Form.Item label='位置' required>
                <SelectGroup value={position} onChange={setPosition} />
            </Form.Item>
            <div className='flex justify-end'>
                <Button
                    disabled={!selectedRowKeys.length}
                    type='primary'
                    onClick={handleImport}
                >
                    导入 {selectedRowKeys.length} 项
                </Button>
            </div>
        </div>
    )
}

export default Import
